import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from 'element-plus'

// 定义通用响应结构
export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}


// 创建一个 Axios 实例
const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 3000,
});

// 定义请求拦截器
axiosInstance.interceptors.request.use(
  (config: any) => {
    // 设置token
    config.headers["Authorization"] = "aa0f26d4-15a0-479c-97f8-0f722e8bae35";
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 定义响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 判断状态码
    if (response.status === 200) {
    }

    // 判断返回的是json数据还是字节流文件
    const contentType: string = response.headers["content-type"];
    const apiResponse: ApiResponse = response.data;

    // 如果是字节流直接返回
    if (contentType.indexOf("application/json") === -1){
      return apiResponse
    }else{

      // 如果是json数据,判断code，正常直接返回，错误弹框
      if (apiResponse.code == 200){
        return apiResponse.data;
      }else{
        ElMessage.error(response.data.msg || '请求失败，请稍后重试')
      }
    } 
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export function get<T>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): any {
  return axiosInstance.get<T>(url, { params, ...config });
}

// 封装 POST 请求
export function post<T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): any {
  return axiosInstance.post<T>(url, data, config);
}

// 封装 PUT 请求
export function put<T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): any {
  return axiosInstance.put<T>(url, data, config);
}

// 封装 DELETE 请求
export function del<T>(url: string, config?: AxiosRequestConfig): any {
  return axiosInstance.delete<T>(url, config);
}
